package com.xiaohao.music_app_m.controller;

import com.xiaohao.music_app_m.bean.User;
import com.xiaohao.music_app_m.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("admin")
public class UserController {
    @Autowired
    private UserMapper userMapper;


    @RequestMapping("user/login")
    public User login(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return null;
        }
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnoreNullValues();
        Example<User> example = Example.of(user, exampleMatcher);
        List<User> all = userMapper.findAll(example);
        if (all.size() >= 1) {
            return all.get(0);
        } else {
            return null;
        }
    }

    @PostMapping("user")
    public User save(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return null;
        }
        return userMapper.save(user);
    }
}
